package demon1;

import java.util.List;

public class MySingleLinkedList implements IMySingleLinkedList {
    class ListNode{
        public int val;
        public ListNode next;

        public ListNode(int val){
            this.val=val;
        }

    }
    public ListNode head;

    public MySingleLinkedList(){

    }
    private void checkIndex(int index)throws IndexNotLegalException{
        if(index>size()||index<0){
            throw new IndexNotLegalException("index位置不合法");
        }
    }
    private ListNode findIndexSubOne(int index){
        int count=0;
        ListNode cur=head;
        while(count==index-1){
            count++;
            cur=cur.next;
        }
        return cur;
    }
    @Override
    public void addFirst(int val) {
        ListNode node=new ListNode(val);
        node.next=this.head;
        this.head=node;
    }

    @Override
    public void addLast(int val) {
        ListNode node=new ListNode(val);
        if(this.head==null){
            this.head=node;
            return;
        }
        ListNode cur=head;
        while(cur.next!=null){
            cur=cur.next;
        }
        cur.next=node;
    }

    @Override
    public void addIndex(int index, int val) {
        try{
            checkIndex(index);
        }catch (IndexNotLegalException e){
            e.printStackTrace();
        }
        if(index==0){
            addFirst(val);
            return;
        }
        if(index==size()){
            addLast(val);
            return;
        }
        ListNode node=new ListNode(val);
        ListNode cur=findIndexSubOne(index);
        node.next=cur.next;
        cur.next=node;

    }

    @Override
    public boolean contains(int key) {
        ListNode cur=head;
        while(cur!=null){
            if(cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {
        if(head==null){
            return;
        }
        if(head.val==key){
            head=head.next;
            return;
        }
        ListNode cur=head;
        while(cur.next!=null){
            if(cur.next.val==key){
                ListNode del=cur.next;
                cur.next=del.next;
                return;
            }
            cur=cur.next;
        }
    }

    @Override
    public void removeAllKey(int key) {

    }

    @Override
    public int size() {
        int count=0;
        ListNode cur=head;
        while(cur!=null){
            count++;
        }
        return count;
    }

    @Override
    public void clear() {

    }

    @Override
    public void display() {
        ListNode cur=this.head;
        while(cur!=null){
            System.out.print(cur.val+"");
            cur=cur.next;
        }
        System.out.println();
    }
}
